package com.ebanma.cloud.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.ebanma.cloud.exception.BusinessException;
import com.ebanma.cloud.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author
 * @version $ Id: GlobalExceptionHandler, v 0.1 2023/03/04 23:00 banma-0369 Exp $
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult<String> defaultErrorHandler(HttpServletRequest request, Exception exception) {
        log.error("Exception: {}" + exception);
        return handleErrorInfo(exception.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseResult<String> checkExceptionHandler(HttpServletRequest request, BusinessException exception) {
        return handleErrorInfo(exception.getMessage());
    }

    private ResponseResult<String> handleErrorInfo(String message) {
        ResponseResult<String> responseEntity = new ResponseResult<>();
        responseEntity.setMessage(message);
        responseEntity.setCode(ResponseResult.ERROR);
        responseEntity.setData(message);
        return responseEntity;
    }
}
